<?php
/*********************************************************************************
* Filename: free_agent.php
* 
* This file presents the user with an interface to sign free agent players
* from their league.  The user first selects the free agent player they
* desire, and then the plasyer to drop from their team.
*
*
* Author: Phillip Peterson
* Date Created: 11/20/2009
**********************************************************************************/
 
//Start the PHP session is it doesn't exist
if (!isset($_SESSION))
	session_start();
//Check if the team is logged in.  If not, redirect the user
//to the login page.
if (!isset($_SESSION['team_id'])){
	include_once "common.php";
	$path = $g_server . $g_login_page;

	header("Location: $path");
	die();
}
   
//The common.php file contains functions and variables common to the 
//entire site
include_once "common.php";

//Store the team id which is stored in the session log
$team_id = $_SESSION['team_id'];

echo "$header_open";
echo "$css_free";
echo "$js_free";
echo "$header_close";
?>

<?php 
    $query = "SELECT * FROM TEAMS WHERE TEAM_ID = $team_id";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $the_league = $row['LEAGUE_ID'];
    
    $query = "SELECT * FROM LEAGUES WHERE LEAGUE_ID = $the_league";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $draft_done = $row['DRAFT_DONE'];
    $scheduled = $row['SCHEDULED'];
    
   	//Query to get the current week for the league
	$query = "SELECT WEEK
			  FROM GAMES
			  WHERE ISNULL(TEAM_1_SCORE)";
	$results = do_query($query, $g_db_name, $g_username);
    
    if (!$draft_done) {
	    $path = $g_server . $g_nodraft_page;
    	header("Location: $path");
    	die();
    }
    else if (!$scheduled) {
        $path = $g_server . $g_noschedule_page;
    	header("Location: $path");
    	die();
    } 
    //Check if the all league games have been played, if so
    //forward the user to the champ page
    else if (mysql_num_rows($results) == 0){
        $path = $g_server . $g_champ;
	    header("Location: $path");
	    die();
    }
    else {
?>

<body onload="freeAgentLoad();">
	<div id="wrapper">
		<div id="inner">
			<?php
				echo "$g_nav_div";
			?>
			<div id="content">
			
			    <h2>Step 1: Select the player you want</h2>
				<div id="container-1">
				<?php

				    //Query to select all of the free agents from the
					//league to display.  Also grap the free agents
					//stats
                    $query = "SELECT * 
                              FROM PLAYERS
                              WHERE PLAYER_ID NOT IN ( 
                                SELECT PLAYER_ID 
                                FROM ROSTER 
                                WHERE TEAM_ID IN (
                                    SELECT TEAM_ID 
                                    FROM TEAMS 
                                    WHERE LEAGUE_ID={$_SESSION['league_id']}))";
				    $result = do_query($query, $g_db_name, $g_username);
				    
				    $player_ids   = array();
				    $player_names = array();
				    
				    while ($row = mysql_fetch_assoc($result)){
				        $player_ids[]   = $row['PLAYER_ID'];
				        $player_names[] = $row['PLAYER_NAME'];
				    }
				    
					//Add the filter field to the screen
				    echo "<div id='search'>";
				    echo "Filter players ";
				    echo "<input id='filter' type='text' size=15 onkeyup='filterPlayers(this);'>";
				    echo "</div>";

		            echo "<ul class='ui-tabs-nav'>";
    		        echo "  <li class='ui-tabs-selected'>
					            <a href='#fragment-1'>
							        <span>Free Agents</span>
					            </a>
				            </li>";
					echo "</ul>";
                
                
					echo "<div id='fragment-1' class='ui-tabs-panel'>
							<table id='free_agents_table'>
							<tr class='table_header'>
							<td width=25></td>
							<td class='name_cell'  onclick='sortTable(this);'>Player</td>
							<td class='point_cell' onclick='sortTable(this);'>Saves</td>
							<td class='point_cell' onclick='sortTable(this);'>Assists</td>
							<td class='point_cell' onclick='sortTable(this);'>Goals</td>
							<td class='point_cell' onclick='sortTable(this);'>Fan Pts</td>
							</tr>";
					       
					//The header query, which gathers the total statistical values for each player according on the given
					//team ID
						$header_query = "SELECT p.PLAYER_ID, p.PLAYER_NAME, p.PLAYER_ISO, 
										 SUM(s.GOALS) as TOTAL_GOALS, SUM(s.ASSISTS) as TOTAL_ASSISTS,
							             SUM(s.SAVES) as TOTAL_SAVES, SUM(s.SCORE) as TOTAL_SCORE
            							 FROM PLAYERS p
							             LEFT OUTER JOIN STATS s
								         ON s.PLAYER_ID = p.PLAYER_ID
								         WHERE p.PLAYER_ID NOT IN ( SELECT PLAYER_ID 
								                                    FROM ROSTER 
								                                    WHERE TEAM_ID IN (SELECT TEAM_ID 
								                                                      FROM TEAMS 
								                                                      WHERE LEAGUE_ID={$_SESSION['league_id']}))
							             GROUP BY p.PLAYER_ID
							             ORDER BY p.PLAYER_NAME ASC";

						$result = do_query($header_query, $g_db_name, $g_username);		

						$align = "align='center'";
						$i = 0;

						// Cycle through all the players are display their totals in a parent row
						while ($row = mysql_fetch_assoc($result)) {
							
							$shade         = (($i+1)%2) ? 'shade_odd' : 'shade_even';
							$name          = $row['PLAYER_NAME'];
							$player_iso    = $row['PLAYER_ISO'];
							$player_id     = $row['PLAYER_ID'];
							$total_goals   = $row['TOTAL_GOALS'];
							$total_assists = $row['TOTAL_ASSISTS'];
							$total_saves   = $row['TOTAL_SAVES'];
							$total_score   = $row['TOTAL_SCORE'];

							$broomball_link = 'http://www.broomball.mtu.edu/user/' . $player_iso;

							echo "<tr class=$shade onmouseover='rowHover(this);' onmouseout='rowUnHover(this);'
							          onclick='swapRadio(this);'>";
                            $color = ($shade == "shade_odd") ? "#E0F0F9" : "#FFFFFF"; 
                            $tag = 'Free Agent_'.$name;
                            echo "
								 <td <input class='radio_button' type='radio' name='trade_for' 
								 			value='freeagent_$player_id' alt='$tag'>
								 <td><a class='bb_link' href='$broomball_link' target='_blank'>$name</a></td>
								 <td $align>$total_saves</td>
								 <td $align>$total_assists</td>
								 <td $align>$total_goals</td>
								 <td $align>$total_score</td>
							</tr>
							";
							
							$i++;
						}
						echo "</table>";
						echo "</div>";
				?>
				</div>
				<div id="step2">
    				<h2>Step 2: Select the player to drop from your team</h2>
				</div>
				
			    <div id="rink">
			    <?php

				    include_once "common.php";

				    $ice_players     = array();
				    $ice_player_id   = array();
				    $bench_players   = array();
				    $bench_player_id = array();

				    $query = "SELECT r.PLAYER_ID, r.POSITION, p.PLAYER_NAME
						      FROM ROSTER r
						      LEFT OUTER JOIN PLAYERS p
						      ON p.PLAYER_ID = r.PLAYER_ID
						      WHERE r.TEAM_ID = $team_id
						      ORDER BY p.PLAYER_NAME";

				    $results = do_query($query, $g_db_name, $g_username);
				    $player_name = array();
				    $player_id = array();

				    while($row = mysql_fetch_assoc($results)){
					    $player_name[] = $row['PLAYER_NAME'];
					    $player_id[]   = $row['PLAYER_ID'];
				    }

				    //Echo each player on the ice
				    for ($i = 0; $i < 10; $i++){
					    $id  = "player_";
					    $id .= ($i+1);
					    $team_name = $_SESSION['team_name'];
					    $tag = $team_name . "_" . $player_name[$i];
					    echo "<img id=$id src='images/rink/red_player_down.png' alt='$tag' name='{$player_id[$i]}'
							       onmouseover='highlightTrade(this);' onmouseout='unhighlightTrade(this);'
							       onclick='tradeClick(this);' class='players'>";
					    $id .= "_label";
					    $temp = explode(" ",$player_name[$i]);
					    $label = $temp[0][0] . ". " . $temp[1];
					    echo "<span class='textLabel_home' id=$id >$label </span>";
				    }

				    echo "<script type='text/javascript'> var g_team_id  = $team_id;</script>"; 

			    ?>
			    </div>
			</div><!--Close content-->

			<div id="sidebar">
			    <div class="player_icon" id="trade_opp_player">
			        <p id="trade_team_name_opp"></p>
			        <p id="trade_player_name_opp"></p>
			    </div>
			    
			    <div id="free_button" onclick="swapPlayers();"
			         onmouseover="swapFreeButtonDown(this);"
			         onmouseout="swapFreeButtonUp(this)"></div>
			         
			    <div class="player_icon" id="trade_home_player">
			        <p id="trade_team_name_home"></p>
			        <p id="trade_player_name_home"></p>
			    </div>
			</div>	
			
			<div id="footer">
			  <?php echo "$footer"; ?>
			</div>
		</div>
	</div>
</body>
<?php } ?>
</html>
